package com.base.cn.platform.os.controller.web.classes.topic;

import com.base.cn.platform.os.common.WebBaseController;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.service.course.classes.ClassesService;
import com.base.cn.platform.os.service.course.classes.member.ClassesMemberService;
import com.base.cn.platform.os.service.course.classes.topic.ClassesTopicService;
import com.base.cn.platform.os.service.course.classes.topic.like.ClassesTopicLikeService;
import com.base.cn.platform.os.service.course.classes.topic.type.ClassesTopicTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * 班级话题
 *
 * @author SK
 * @since 2018-05-28
 */
@Controller
@RequestMapping("/web/classes/topic")
public class WebClassesTopicController extends WebBaseController {

    @Autowired
    private ClassesService classesService;
    @Autowired
    private ClassesTopicLikeService classesTopicLikeService;
    @Autowired
    private ClassesMemberService classesMemberService;
    @Autowired
    private ClassesTopicService classesTopicService;
    @Autowired
    private ClassesTopicTypeService classesTopicTypeService;

    /**
     * 班级话题列表
     *
     * @param classesId 班级id
     * @param order     排序 1.最新 2.最热
     * @param classify     话题分类
     * @param classify     话题分类
     * @return 班级话题列表页面
     */
    @RequestMapping("/ajaxTopicList")
    public String ajaxTopicList(Model model,
                                HttpServletRequest request,
                                @RequestParam(value = "classesId", required = false) BigDecimal classesId,
                                @RequestParam(value = "title", required = false) String title,
                                @RequestParam(value = "order", required = false) Integer order,
                                @RequestParam(value = "classify", required = false) Integer classify,
                                @RequestParam(value = "joined", required = false) Boolean joined,
                                @RequestParam(value = "currentPage", required = false, defaultValue = "1") Integer currentPage) {
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        Map<String, Object> params = new HashMap<>();
        params.put("classesId", classesId);
        params.put("title", title);
        params.put("classify", classify);
        params.put("joined", joined);
        params.put("userId",userId);
        params.put("status", 1);
        Map<String, Object> dataMap = classesTopicService.findClassesTopicListPage(params, currentPage, null, order, true, false, true);
        if (StringUtils.isNotEmpty(dataMap)){
            List<Map<String, Object>> list = (List<Map<String, Object>>) dataMap.get("list");
            list.forEach(e->{
                String context = (String) e.get("content");
                String replaceContext = context.replaceAll("<img.*?>", "");
                e.put("content",replaceContext);
            });
        }
        model.addAttribute("dataMap", dataMap);
        return resultPage("/classes/topic/ajax-topic-list");
    }
    /**
     * 初始化发布话题页面
     *
     * @param classesId 班级id
     * @return 发布话题页面
     */
    @RequestMapping("/initPublish")
    public String initPublish(Model model,
                              @RequestParam("classesId") BigDecimal classesId) {
        model.addAttribute("classesId", classesId);
        List<Map<String, Object>> classifies = classesTopicTypeService.getClassesTopicType(classesId);
        model.addAttribute("classifies", classifies);
        return resultPage("/classes/topic/init-publish");
    }

    /**
     * 话题详情
     *
     * @param topicId 话题id
     * @return 话题详情页面
     */
    @RequestMapping("/info")
    public String info(Model model,
                       HttpServletRequest request,
                       @RequestParam("id") BigDecimal topicId) {
        // 话题
        Map<String, Object> topic = classesTopicService.findClassesTopicById(topicId, true, true, true, true);
        model.addAttribute("topic", topic);
        // 是否登录
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        model.addAttribute("login", DataUtil.idIsNotNull(userId));
        // 是否加入班级
        Number classesId = (Number) topic.get("classesId");
        boolean joined = classesMemberService.joined(new BigDecimal(classesId.toString()), userId);
        model.addAttribute("joined", joined);
        if(!joined){//判断是否具有浏览权限
            Integer lookPermission = (Integer) topic.get("lookPermission");
            if(lookPermission==3 || lookPermission==2 && !DataUtil.idIsNotNull(userId)){
                return redirect(request,"/web/classes/info?id="+topic.get("classesId"));
            }
        }
        // 前10个点赞的人
        Map<String, Object> params = new HashMap<>();
        params.put("topicId", topicId);
        List<Map<String, Object>> topicLikeList = classesTopicLikeService.findClassesTopicLikeList(params, 10, true);
        model.addAttribute("topicLikeList", topicLikeList);
        // 是否点过赞
        params.put("userId", userId);
        List<Map<String, Object>> one = classesTopicLikeService.findClassesTopicLikeList(params, 1, false);
        model.addAttribute("liked", ObjectUtils.isNotEmpty(one));
        // 班级详情
        Map<String, Object> classes = classesService.findClassesById(new BigDecimal(classesId.toString()), false, false, false, false, 0);
        model.addAttribute("classes", classes);
        // 班级话题统计
        Map<String, Object> statistics = classesTopicService.classesTopicStatistics(topicId, null);
        model.addAttribute("statistics", statistics);
        // 话题推荐
        List<Map<String, Object>> recommendList = classesTopicService.findClassesTopicList(Collections.emptyMap(), 5, 2, false, false, false);
        model.addAttribute("mobilePathShare", "/mobile/class/topic/info?id="+topicId);
        //获取当前班级访问路径(用于购买课程成功后的回调)
        String requestURL = request.getRequestURL().toString();
        requestURL += "?id="+topicId;
        model.addAttribute("requestURL",requestURL);
        model.addAttribute("recommendList", recommendList);
        return resultPage("/classes/topic/info/topic-info");
    }

    /**
     * 保存话题
     *
     * @param params 参数
     * @return 保存结果
     */
    @RequestMapping("/saveTopic")
    @ResponseBody
    public Map<String, Object> saveTopic(HttpServletRequest request,
                                         @RequestBody Map<String, Object> params) {
        Object gapLeft = params.remove("gapLeft");
        Object moveLeft = params.remove("moveLeft");
        if (Objects.nonNull(gapLeft) && Objects.nonNull(moveLeft)) {
            if (StringUtils.isNumber(gapLeft.toString() + moveLeft.toString())) {
                int gap = Integer.parseInt(gapLeft.toString());
                int move = Integer.parseInt(moveLeft.toString());
                if (gap + move > 0 && Math.abs(gap - move) <= 5) {
                    String classesIds = params.remove("classesId").toString();
                    BigDecimal createUserId = webMobileLoginUtil.getLoginUserId(request);
                    //处理xss过滤器转化的字符
                    params.put("content", this.disposeontentC(params.get("content").toString()));
                    params.put("createUserId", createUserId);
                    params.put("source", 1);
                    return classesTopicService.saveClassesTopic(params, classesIds);
                }
            }
        }
        return ResultUtil.ERROR("验证码错误");
    }

    /**
     * 处理script标签和过滤掉里边的javascript开头的关键字
     * @param content
     * @return
     */
    private   String disposeontentC(String content ){
        content = this.ToDBC(content);
        return content = content.replaceAll("(?i)<script[^>]*>[\\d\\D]*?</script>","");
    }

    /**
     * 全角字符转回半角字符
     * @param input
     * @return
     */
    private  String ToDBC(String input) {
        char c[] = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == '\u3000') {
                c[i] = ' ';
            } else if (c[i] > '\uFF00' && c[i] < '\uFF5F') {
                c[i] = (char) (c[i] - 65248);
            }
        }
        String returnString = new String(c);
        return returnString;
    }
}
